from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db.models import Sum, F, Q
from django.utils import timezone # <--- 添加这一行
from .models import Warehouse, Inventory, InventoryRecord, PurchaseOrder, PurchaseOrderItem # 确保 PurchaseOrderItem 也已导入
from .serializers import (
    WarehouseSerializer, 
    InventorySerializer, 
    InventoryRecordSerializer, 
    PurchaseOrderSerializer, 
    CreatePurchaseOrderSerializer, # 确保 CreatePurchaseOrderSerializer 也已导入
    UpdatePurchaseOrderStatusSerializer # 确保 UpdatePurchaseOrderStatusSerializer 也已导入
)
from users.permissions import IsAdmin, PurchaserPermission, CanManageInventory
from products.models import Product
from decimal import Decimal, InvalidOperation

class WarehouseViewSet(viewsets.ModelViewSet):
    queryset = Warehouse.objects.all()
    serializer_class = WarehouseSerializer
    
    def get_permissions(self):
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            return [IsAdmin()]
        return [permissions.IsAuthenticated()]

class InventoryViewSet(viewsets.ModelViewSet):
    queryset = Inventory.objects.all()
    serializer_class = InventorySerializer
    
    def get_permissions(self):
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            return [IsAdmin() | PurchaserPermission()]
        return [permissions.IsAuthenticated()]
    
    def get_queryset(self):
        queryset = Inventory.objects.all()
        warehouse_id = self.request.query_params.get('warehouse_id')
        product_name = self.request.query_params.get('product_name')
        status = self.request.query_params.get('status')
        
        if warehouse_id:
            queryset = queryset.filter(warehouse_id=warehouse_id)
        if product_name:
            queryset = queryset.filter(product__name__icontains=product_name)
        if status:
            queryset = queryset.filter(status=status)
            
        return queryset
    
    @action(detail=False, methods=['get'])
    def low_stock(self, request):
        # 获取库存低于最低库存的商品
        low_stock_items = Inventory.objects.filter(current_stock__lt=F('min_stock'))
        serializer = self.get_serializer(low_stock_items, many=True)
        return Response({
            'code': 200,
            'message': '获取成功',
            'data': serializer.data
        })
    
    @action(detail=False, methods=['post'])
    def adjust(self, request):
        # 库存调整API
        inventory_id = request.data.get('inventory_id')
        operation_type = request.data.get('operation_type')
        quantity = request.data.get('quantity')
        source_warehouse_id = request.data.get('source_warehouse_id')
        target_warehouse_id = request.data.get('target_warehouse_id')
        related_order_id = request.data.get('related_order_id')
        note = request.data.get('note', '')
        
        try:
            inventory = Inventory.objects.get(id=inventory_id)
        except Inventory.DoesNotExist:
            return Response({
                'code': 404,
                'message': '库存不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        
        # 创建库存记录
        record_data = {
            'inventory': inventory,
            'operation_type': operation_type,
            'quantity': quantity,
            'operator': request.user,
            'note': note
        }
        
        # 根据操作类型处理库存
        if operation_type == 'in':
            # 入库操作
            inventory.current_stock += int(quantity)
        elif operation_type == 'out':
            # 出库操作
            if inventory.current_stock < int(quantity):
                return Response({
                    'code': 400,
                    'message': '库存不足'
                }, status=status.HTTP_400_BAD_REQUEST)
            inventory.current_stock -= int(quantity)
        elif operation_type == 'adjust':
            # 直接调整库存
            inventory.current_stock = int(quantity)
        elif operation_type == 'transfer':
            # 库存转移
            if not source_warehouse_id or not target_warehouse_id:
                return Response({
                    'code': 400,
                    'message': '转移操作需要提供源仓库和目标仓库'
                }, status=status.HTTP_400_BAD_REQUEST)
                
            if inventory.current_stock < int(quantity):
                return Response({
                    'code': 400,
                    'message': '库存不足'
                }, status=status.HTTP_400_BAD_REQUEST)
                
            # 减少源仓库库存
            inventory.current_stock -= int(quantity)
            
            # 增加目标仓库库存
            try:
                source_warehouse = Warehouse.objects.get(id=source_warehouse_id)
                target_warehouse = Warehouse.objects.get(id=target_warehouse_id)
                record_data['source_warehouse'] = source_warehouse
                record_data['target_warehouse'] = target_warehouse
                
                # 查找或创建目标仓库的库存记录
                target_inventory, created = Inventory.objects.get_or_create(
                    product=inventory.product,
                    warehouse_id=target_warehouse_id,
                    defaults={
                        'min_stock': inventory.min_stock,
                        'max_stock': inventory.max_stock,
                        'purchase_date': inventory.purchase_date,
                        'expiry_date': inventory.expiry_date,
                        'status': inventory.status
                    }
                )
                target_inventory.current_stock += int(quantity)
                target_inventory.save()
                
            except Warehouse.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '仓库不存在'
                }, status=status.HTTP_404_NOT_FOUND)
        else:
            return Response({
                'code': 400,
                'message': '不支持的操作类型'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 更新库存状态
        if inventory.current_stock < inventory.min_stock:
            inventory.status = 'warning'
        elif inventory.max_stock and inventory.current_stock > inventory.max_stock:
            inventory.status = 'overflow'
        else:
            inventory.status = 'normal'
        
        # 保存库存更新
        inventory.save()
        
        # 如果有关联订单，添加到记录中
        if related_order_id:
            from orders.models import Order
            try:
                order = Order.objects.get(id=related_order_id)
                record_data['related_order'] = order
            except Order.DoesNotExist:
                pass
        
        # 创建库存记录
        record = InventoryRecord.objects.create(**record_data)
        
        return Response({
            'code': 200,
            'message': '调整成功',
            'data': {
                'current_stock': inventory.current_stock
            }
        })

class InventoryRecordViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = InventoryRecord.objects.all().order_by('-created_at')
    serializer_class = InventoryRecordSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        queryset = InventoryRecord.objects.all().order_by('-created_at')
        inventory_id = self.request.query_params.get('inventory_id')
        operation_type = self.request.query_params.get('operation_type')
        start_date = self.request.query_params.get('start_date')
        end_date = self.request.query_params.get('end_date')
        
        if inventory_id:
            queryset = queryset.filter(inventory_id=inventory_id)
        if operation_type:
            queryset = queryset.filter(operation_type=operation_type)
        if start_date:
            queryset = queryset.filter(created_at__gte=start_date)
        if end_date:
            queryset = queryset.filter(created_at__lte=end_date)
            
        return queryset
    
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'total': self.paginator.page.paginator.count,
                    'items': serializer.data
                }
            })
        
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'code': 200,
            'message': '获取成功',
            'data': {
                'total': queryset.count(),
                'items': serializer.data
            }
        })

class PurchaseOrderViewSet(viewsets.ModelViewSet):
    queryset = PurchaseOrder.objects.all().order_by('-created_at')
    serializer_class = PurchaseOrderSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        queryset = super().get_queryset()
        
        # 过滤条件
        order_number = self.request.query_params.get('order_number')
        supplier = self.request.query_params.get('supplier')
        status = self.request.query_params.get('status')
        start_date = self.request.query_params.get('start_date')
        end_date = self.request.query_params.get('end_date')
        
        if order_number:
            queryset = queryset.filter(order_number__icontains=order_number)
        if supplier:
            queryset = queryset.filter(supplier__icontains=supplier)
        if status:
            # 支持多个状态的过滤
            status_list = status.split(',')
            queryset = queryset.filter(status__in=status_list)
        if start_date:
            queryset = queryset.filter(created_at__gte=start_date)
        if end_date:
            queryset = queryset.filter(created_at__lte=end_date)
            
        return queryset
    
    def create(self, request, *args, **kwargs):
        serializer = CreatePurchaseOrderSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 创建采购订单
        total_amount = Decimal('0.0')
        for item in serializer.validated_data['items']:
            total_amount += Decimal(str(item['quantity'])) * Decimal(str(item['unit_price']))
        
        purchase_order = PurchaseOrder.objects.create(
            supplier=serializer.validated_data['supplier'],
            purchaser=request.user,
            total_amount=total_amount,
            remark=serializer.validated_data.get('remark', '')
        )
        
        # 创建采购订单明细
        for item in serializer.validated_data['items']:
            product = Product.objects.get(id=int(item['product_id']))
            warehouse = Warehouse.objects.get(id=int(item['warehouse_id']))
            
            PurchaseOrderItem.objects.create(
                purchase_order=purchase_order,
                product=product,
                quantity=int(item['quantity']),  # 转换为整数
                unit_price=Decimal(str(item['unit_price'])),  # 转换为Decimal
                warehouse=warehouse
            )
        
        return Response({
            'code': 200,
            'message': '创建成功',
            'data': {
                'order_number': purchase_order.order_number,
                'total_amount': purchase_order.total_amount
            }
        })
    
    @action(detail=True, methods=['put'])
    def status(self, request, pk=None):
        purchase_order = self.get_object()
        serializer = UpdatePurchaseOrderStatusSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        new_status = serializer.validated_data['status']
        note = serializer.validated_data.get('note', '')
        
        # 检查状态变更是否合法
        if purchase_order.status == 'cancelled':
            return Response({
                'code': 400,
                'message': '已取消的订单不能更改状态'
            }, status=400)
        
        if purchase_order.status == 'received' and new_status != 'cancelled':
            return Response({
                'code': 400,
                'message': '已收货的订单只能取消'
            }, status=400)
        
        # 更新状态
        purchase_order.status = new_status
        if note:
            purchase_order.remark = (purchase_order.remark or '') + f'\n[{timezone.now().strftime("%Y-%m-%d %H:%M:%S")}] {note}'
        purchase_order.save()
        
        # 如果状态是已收货，更新库存
        if new_status == 'received':
            for item in purchase_order.items.all():
                # 查找或创建库存记录
                inventory, created = Inventory.objects.get_or_create(
                    product=item.product,
                    warehouse=item.warehouse,
                    defaults={
                        'current_stock': 0,
                        'min_stock': item.product.min_stock,
                        'status': 'normal'
                    }
                )
                
                # 更新库存
                old_stock = inventory.current_stock
                inventory.current_stock += item.quantity
                inventory.save()
                
                # 创建库存操作记录
                InventoryRecord.objects.create(
                    inventory=inventory,
                    operation_type='in',
                    quantity=item.quantity,
                    operator=request.user,
                    # related_order=purchase_order, # 移除或注释掉这一行
                    note=f'采购订单 {purchase_order.order_number} 收货'
                )
        
        return Response({
            'code': 200,
            'message': '更新成功'
        })